package jm.data.structure.leet_code;

import jm.data.structure.tree.BinaryTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Description https://leetcode-cn.com/problems/invert-binary-tree/
 * @date 2022/4/11 12:56
 */
public class _226翻转二叉树 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 前序遍历实现翻转
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null){
            return null;
        }

        // 交换节点
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    /**
     * 层级遍历实现翻转
     * @param root
     * @return
     */
    public TreeNode invertTreeLevel(TreeNode root){
        if (root == null) {
            return root;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();

            // 交换节点
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;

            if (node.left != null){
                queue.offer(node.left);
            }
            if (node.right != null){
                queue.offer(node.right);
            }
        }
        return root;
    }
}
